package com.example.spring.exercise.security;

import com.example.spring.exercise.entity.UserEntity;
import com.example.spring.exercise.entity.UserRoleEntity;
import com.example.spring.exercise.repository.UserRepository;
import com.example.spring.exercise.repository.UserRoleRepository;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author : zhayh
 * @date : 2021-4-18 17:10
 * @description : 令牌工具类
 */

//@Component
public class TokenProvider {
    @Resource
    private UserRepository userRepository;

    @Resource
    private UserRoleRepository userRoleRepository;

    public String createToken(Authentication user) {
        return "thisistoken." + user.getName();
    }

    // 校验用户令牌是否合法
    public boolean validateToken(String token) {
        return token.startsWith("thisistoken");
    }

    public Authentication getUser(String token) {
        // 1. 解析令牌。的搭配SpringSecurity能够使用的Authentication，实现逻辑与UserDetailService类似
        String login = token.split("\\.")[1];
        Optional<UserEntity> userEntityOptional = userRepository.findByLogin(login);
        if (userEntityOptional.isEmpty()) {
            return null;
        }
        UserEntity userEntity = userEntityOptional.get();
        // 2. 获取账户对应角色
        List<UserRoleEntity> roles = userRoleRepository.findByUserLogin(userEntity.getLogin());
        //将账户角色组成SpringSecurity的权限列表
        List<SimpleGrantedAuthority> roleList=new
                ArrayList<SimpleGrantedAuthority>();
        for (UserRoleEntity role : roles) {
            roleList.add(new SimpleGrantedAuthority(role.getRoleName()));
        }
        // 3. 构造为SpringSecurity的验证，并返回交给Spring Security进行校验
        return new UsernamePasswordAuthenticationToken(userEntity, token, roleList);
    }
}
